package com.zjw.touchscreen.listener;

import android.annotation.SuppressLint;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;
import com.zjw.touchscreen.bluetooth.MouseHelper;
import lombok.Data;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressLint("NewApi")
public class TouchBoardListener implements View.OnTouchListener {

    private SeekBar seekBar;
    private AtomicInteger mark;
    private volatile float x = 0;
    private volatile float y = 0;
    private boolean isSlide = false;

    private final LinkedList<Point> points = new LinkedList<>();

    public TouchBoardListener(SeekBar seekBar, AtomicInteger mark) {
        this.seekBar = seekBar;
        this.mark = mark;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                y = event.getY();
                isSlide = x > v.getWidth() - 100;
                break;
            case MotionEvent.ACTION_MOVE:
//                if (!isSlide) {
                move(event);
//                    break;
//                }
//                rightSlide(event);
                break;
        }
        return false;
    }

    private Integer count = 0;

    private void rightSlide(MotionEvent event) {
        if (count % 4 == 0) {
            count = 0;
            float yOffset = event.getY() - y;
            y = event.getY();
            yOffset = yOffset > 0 ? -1 : yOffset < 0 ? 1 : 0;
            MouseHelper.sendData(false, false, false, 0, 0, (int) yOffset);
        }
        count++;
    }

    private void move(MotionEvent event) {
        float speed = seekBar.getProgress();
        speed = 1 + speed / 10;
        float xOffset = event.getX() - x;
        float yOffset = event.getY() - y;
        x = event.getX();
        y = event.getY();
        xOffset = xOffset * speed > 127 ? 127 : xOffset * speed;
        xOffset = xOffset * speed < -127 ? -127 : xOffset * speed;
        yOffset = yOffset * speed > 127 ? 127 : yOffset * speed;
        yOffset = yOffset * speed < -127 ? -127 : yOffset * speed;
        Point point = new Point();
        point.setXOffset(xOffset);
        point.setYOffset(yOffset);
        if (xOffset > -1 && xOffset < 1 && yOffset > -1 && yOffset < 1) {
            return;
        }
        if (mark.get() == 0) {
            mark.incrementAndGet();
        }
        MouseHelper.sendData(false, false, false, (int) xOffset, (int) yOffset, 0);
    }

    @Data
    private static class Point {
        private float xOffset;
        private float yOffset;
    }
}
